<?php

namespace App\Http\Controllers;

use App\SendOrder;
use App\Support\User;
use Illuminate\Http\Request;

class SendOrdersController extends Controller {
	use Search;

	protected $model, $user;

	public function __construct(SendOrder $sendOrder, User $user) {
		$this->model = $sendOrder;
		$this->user = $user;
	}

	public function index(Request $request) {
		$business = $this->getBusiness();
		return view('sendOrders.index', compact('business'));
	}

	public function list(Request $request) {
		$page = $request->get('page', 1);
		$pageSize = $request->get('pageSize', 10);
		$where = $this->getSearchWhere($request);
		$where .= ' and contacts is not null';
		$nums['orderNum'] = $this->model->whereRaw($where . ' and status = 0')->count();
		$nums['sendOrderNum'] = $this->model->whereRaw($where . ' and status = 1')->count();
		$pageNums = ceil($nums['orderNum'] / $pageSize);
		$orders = $this->model->whereRaw($where)->offset(($page - 1) * $pageSize)->limit($pageSize)->get();
		return view('sendOrders.list', compact('orders', 'page', 'pageNums', 'nums'));
	}

	public function detail($id) {
		$order = $this->model->findOrFail($id);
		return view('sendOrders.detail', compact('order'));
	}

	public function activityShip(SendOrder $sendOrder, Request $request) {
		$this->validate($request, [
			'ship_num' => 'required|numeric',
			'ship_company' => 'required',
			'decimal' => 'required|numeric',
		]);
		$sendOrder->ship_num = $request->ship_num;
		$sendOrder->ship_company = $request->ship_company;
		$sendOrder->decimal = $request->decimal;
		$sendOrder->status = 1;
		$sendOrder->save();

		$content = '恭喜你免费获得' . $sendOrder->products . '！商家已发货~（点击查看详情）';
		$this->user->modifyNotice($sendOrder->user_id, $sendOrder->id, '中奖通知', $content);
		return ['code' => 0, 'msg' => 'success'];
	}
}
